package com.lloydfinch.repolayer;


import com.lloydfinch.bblayer.UserBean;
import com.lloydfinch.ldlayer.dao.IUserDao;
import com.lloydfinch.ldlayer.dao.UserDaoHelper;
import com.lloydfinch.rdlayer.UserApi;

import java.util.List;

public class UserRepository {

    private IUserDao userDao = new UserDaoHelper();

    /**
     * sync
     *
     * @return
     */
    public List<UserBean> getVipUsers() {
        List<UserBean> allVipUser = userDao.getAllVipUser();
        if (allVipUser != null) return allVipUser;

        UserApi.getVipUsers(userBeans -> {
            if (checkData(userBeans)) {
                this.userDao.storeUsers(userBeans);
            }
        });

        return this.userDao.getAllVipUser();
    }

    /**
     * async
     *
     * @param onGetUsers
     */
    public void getVipUsers(OnGetUsers onGetUsers) {
        List<UserBean> allVipUser = userDao.getAllVipUser();
        if (allVipUser != null) onGetUsers.onResult(allVipUser);

        UserApi.getVipUsers(userBeans -> {
            if (checkData(userBeans)) {
                onGetUsers.onResult(userBeans);
                this.userDao.storeUsers(userBeans);
            }
        });
    }

    public void addUser(UserBean userBean) {
        userDao.storeUser(userBean);
    }

    private boolean checkData(List<UserBean> userBeans) {
        // 校验数据是否合法
        return true;
    }

    public interface OnGetUsers {
        void onResult(List<UserBean> users);
    }
}
